use std::fs::{File, metadata};
use std::io::{self, Write, Read, BufRead, BufReader};

fn write(filename: String, lines: Vec<String>) -> io::Result<()> {
    let mut file = File::create(filename)?;
    for line in lines {
        file.write_all(line.as_bytes())?;
        file.write_all(b"\n")?;
    }
    Ok(())
}

fn gen_lines(n: usize) -> Vec<String> {
    let mut lines = Vec::new();
    for i in 0..n {
        lines.push(format!("{} - Iceman", i + 1));
    }
    lines
}

fn read(filename: String) -> io::Result<String> {
    let mut file = File::open(filename)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}

fn print_lines(filename: String) -> io::Result<()> {
    let file = File::open(filename)?;
    let body = BufReader::new(file);
    for line in body.lines() {
        let line = line?;
        println!(" = > {}", line);
    }
    Ok(())
}

fn main() {
    let filename = String::from("output.txt");
    let lines = gen_lines(5);
    write(filename.clone(), lines).unwrap();
    let result = read(filename.clone()).unwrap();
    println!("文件内容: \n{}", result);
    print_lines(filename.clone()).unwrap();
    // 文件信息
    let fm = metadata(&filename).unwrap();
    println!("{:?}", fm);
}
